﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.UpdateServices.Administration;
using Telerik.Web.Mvc;
using System.Collections;
using WsusWebAdmin.Web.Helpers;

namespace WsusWebAdmin.Web.Controllers
{
    public class UpdatesController : UpdateServerBaseController
    {
        //
        // GET: /Updates/

        public ActionResult Unapproved()
        {                        
            return View();
        }

        [GridAction]
        public ActionResult UnapprovedGrid()
        {
            var updates = UpdateServer.GetUpdates(ApprovedStates.NotApproved,
                                                   DateTime.MinValue,
                                                   DateTime.MaxValue,
                                                   null,
                                                   null);


            var model = new List<IUpdate>();
            foreach (IUpdate item in updates)
            {
                model.Add(item);
            }

            return View(new GridModel<IUpdate>
            {
                Data = model
            });
        }


        public ActionResult UpdateDetails(Guid id)
        {
            IUpdate update = UpdateServer.GetUpdate(new UpdateRevisionId(id));            

            return View(update);
        }

        [HttpPost]
        [JsonRequest("selectedUpdates",typeof(Guid[]))]
        public ActionResult ApproveDialog(Guid[] selectedUpdates)
        {
            var groups= UpdateServer.GetComputerTargetGroups().AsEnumerable<IComputerTargetGroup>();


            return PartialView("ApproveDialog", new UpdatesApproveDialogViewModel
            {
                Groups = groups,
                SelectedUpdates = selectedUpdates ?? new Guid[0]
            });
        }

        public ActionResult Approve(Guid[] selectedUpdates, Guid[] groups)
        {
            var updateId = selectedUpdates[0]; //Due to limitaions of Telerik grid only one update can be approved at once
            var update = UpdateServer.GetUpdate(new UpdateRevisionId(updateId));
            foreach (var groupId in groups)
            {
                var group = UpdateServer.GetComputerTargetGroup(groupId);
                update.Approve(UpdateApprovalAction.Install, group);                
            }

            return PartialView("UpdatesApproved");
        }

        [HttpPost]
        [JsonRequest("selectedUpdates", typeof(Guid[]))]
        public ActionResult RejectUpdate(Guid[] selectedUpdates)
        {
            var updateId = selectedUpdates[0]; //Due to limitaions of Telerik grid only one update can be approved at once
            var update = UpdateServer.GetUpdate(new UpdateRevisionId(updateId));
            update.Decline();
            return Content("");
        }
    }
}
